/**
 * 角色类公用方法
 */

// 出招共用函数
const baseTool = require('./base-tool');
const baseFile = require('./base-file')
const CURD = require('../compontents/DB/CURDClass')
const log = require('./log')
const md5 = require("md5-node");

let baseRole = {
    // 是否有敌人
    offensive_target(me) {
        let enemy = me.enemy;
        let sz = enemy.length;

        if( !sz ) return 0;
        if( sz > 4 ) sz = 4;

        if( sz > 0 ) {
            return enemy[baseTool.random(0, sz)];
        } else {
            return 0;
        }
        return true;
    },
    skill_power( me, skill, usage ) {
        let level, power;
        // 特殊武功等级
        level = me.basic[skill];
        switch ( usage ) {
            case SKILL_USAGE_ATTACK:
                // 攻击
                level += me.temp.attack;
                break;
            case SKILL_USAGE_DEFENSE:
                // 防御
                level += me.temp.defense;
            case SKILL_USAGE_PARRY:
                // 架招
                // 先天臂力 最大 30
                // 后天臂力 最大 9999
                // 技能等级 最大 10000
                // 角色精力 最大 999999
                //     (40%先天臂力/先天臂力+20%（(后天臂力t+1%技能等级)/9999）+20%技能等级/10000+20%角色精力/999999)*（先天臂力*1.3）
                level = .4 * me.str/me.str + .2 * ((me.str_last + .1 * level)/me.str_last +.2*level/level+.2*me.str_last /me.str_last) * (me.str*1.3)
                // 缺少：me.temp.fight 算法
                // if ( me.is_fighting )
                //     level += level * (me.temp.fight + skill ) / 100;
        }

        // 缺少：combat_exp算法
        if ( level < 1 )
            power = me.combat_exp / 3600;
        else
            power = ( Math.sqrt( level )  * level * level  + me.combat_exp) / 2 / 300;



        // 返回架招
        if (usage == SKILL_USAGE_PARRY) return Math.floor(level);

        // 返回攻击值
        if ( usage == SKILL_USAGE_ATTACK ) return Math.floor(power * me.str / 5 / 100) ;

        // 返回躲闪值
        if ( skill == "dodge" ) return Math.floor(power / me.dex );
    },
    adj_msg( result, weapon, attack_skill ) {
        let wname = weapon.name_ch;
        let isweapon = Object.keys(weapon).length>0;

        let limbs = ["上身", "下身", "身上"];
        let limb = limbs[baseTool.random(0, limbs.length-1)];

        if ( isweapon ) {
             // 原有的短兵器逻辑，已经放弃
            // if ( weapon->query_amount() && weapon->query( "skill_type" ) != "throwing" )
            // sscanf( weapon->short(), "%s(%*s", wname );
             wname = weapon.name;
             result = result.replace( /\$w/, wname );
        }
        if ( attack_skill == "finger" )
            result = result.replace( /\$w/, "手指" );
        else if ( attack_skill == "cuff" )
            result = result.replace( /\$w/, "拳头" );
        else if ( attack_skill == "strike" )
            result = result.replace( /\$w/, "手掌" );
        else if ( attack_skill == "claw" )
            result = result.replace( /\$w/, "手爪" );
        else
            result = result.replace( /\$w/, "" );

        result = result.replace( /\$l/, limb );

        return result;
    },
    end_fight(victim) {
        return `${victim.name_ch}挣扎了几下，倒在地上成为一具尸体。`;
    },
    message_damage(damage, victim) {
        return `<p>你对${victim.name_ch}造成了<font class="Red">${damage}</font>点攻击伤害</p>`
    },
    // 获取称呼
    nickname() {
        let exp = global.USERINFO.exp;
        console.log(exp)
        //    少年、10000 - 499999 十万
        //    小伙、500000 - 999999
        //    少侠、1000000 - 4999999 百万
        //    大侠、5000000 - 49999999
        //    豪侠、
        //    宗师、
        //    泰斗、
        //    武宗、
        //    武神、
        //    武圣、
        //    武帝、
        if (exp <= 499999){
            return '少年'
        } else if (exp>=500000 && exp<=999999) {
            return '小伙'
        } else if (exp>=1000000 && exp<=4999999) {
            return '少侠'
        } else if (exp>=5000000 && exp<=49999999) {
            return '大侠'
        }
    },
    // 姓名转换
    message_vision(msg, me, victim='') {
        let my_gender, he_gender, my_name, he_name;
        let str1, str2, str3, str4;

        my_name = me.name_ch;
        my_gender = me.gender;

        str1 = msg.replace(/\$P/, this.gender_self(my_gender))
        str2 = str1.replace(/\$N/, this.gender_self(my_gender));

        if (victim) {
            he_name = victim.name_ch;
            he_gender = victim.gender;
            str3 = str2.replace(/\$n/, he_name);
            str4 = str3.replace(/\$n/, he_name);
        }

        return str4;
    },
    // 性别
    gender_pronoun(sex) {
        switch(sex) {
            case "中性神":	return "他";
            case "男性":	return "他";
            case "无性":    return "他";
            case "女性":	return "她";
            case "雄性":
            case "雌性":	return "它";
            default: return "它";
        }
    },
    // 自身性别
    gender_self(g){
        switch(g) {
            case 0: return "你";
            default: return "你";
        }
    },
    /**
     * 查询某个房间在线人数
     * @param hasInfo number 未出新手村之前
     * @param hasInfo string 出新手村之后传房间名
     * @returns {Promise<void>}
     */
    async get_online_list(hasInfo = '', uid = '', ename = '') {
        let room = '';

        if (typeof hasInfo == 'number') {
            if (hasInfo == 1) room = 'birth/birth-room'
            if (hasInfo == 2) room = 'wuguan/dating'
            if (hasInfo == 3) room = 'yangzhou/kezhan'
        } else {
            room = hasInfo
        }

        const select_rows = await CURD.select({
            fields: '`room`,`uid_list`',
            table: 'online_list',
            where: [{wfield: 'room', wvalue: room}]
        });

        // return select_rows;

        if (!select_rows.length) {
            // 没有房间数据，自动创建
            const insert_rows = await CURD.insert({
                table: `online_list`,
                fields: 'room, uid_list',
                values: `${room}, ${uid}_${ename},`,
            })
            if (insert_rows.affectedRows) {
                return {
                    room: room,
                    uid_list: `${uid}_${ename},`
                }
            }
        } else {
            return select_rows[0];
        }
    },
    /**
     * 上线操作
     * 房间数据处理
     * @param data 当前房间
     * @param uid
     */
    async room_data_handle(data, uid, ename, hasInfo) {
        // 文件操作
        // const path = './online-data.txt';
        // baseFile.read(path, uid).then((content)=>{
        //     baseFile.write(path, content, uid)
        // })

        // uid_list：去重
        const uidReg = `${uid}_${ename},`
        const regExp = new RegExp(uidReg)
        if (data.uid_list.indexOf(uid)>-1) data.uid_list = data.uid_list.replace(regExp, '');

        // 重新拼装
        const uid_list = `${!data.uid_list ? uidReg : data.uid_list + uidReg}` ;

        // 更新表数据
        const up_rows = await CURD.update({
            table: 'online_list',
            fields: [`uid_list='${uid_list}'`],
            where: [{wfield: 'room', wvalue: data.room}]
        })

        // 返回最新的数据
        return {
            room_data: {
                room: data.room,
                uid_list: uid_list,
            },
            hasInfo: hasInfo
        };
    },
    /**
     * 离线操作
     * 将角色从当前房间删除
     * @param room 当前房间
     */
    async offOnline(room, uid, ename) {
        const select_rows = await CURD.select({
            fields: '`room`,`uid_list`',
            table: 'online_list',
            where: [{wfield: 'room', wvalue: room}]
        });
        const new_uid_list = select_rows[0].uid_list.replace(new RegExp(`${uid}_${ename},`),'');
        
        await CURD.update({
            table: 'online_list',
            fields: [`uid_list='${new_uid_list}'`],
            where: [{wfield: 'room', wvalue: room}]
        })
    },
    // 账号已经注册，查询是否有角色信息
    async get_user_info(uid) {
        const user_info_rows = await CURD.select({
            fields: '`birth`',
            table: 'user_info',
            where: [{wfield: 'uid', wvalue: uid}]
        })

        if (user_info_rows.length) {
            return user_info_rows[0].birth;
        } else {
            return -1;
        }
    }
}
module.exports = baseRole;